<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
        :show-row-hover="true"
        class="treeTable"
      >
        <template slot="isok" scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color:lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <template slot="order" scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditGoodsDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteHandle(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @closed="addCateDialogClosed"
    >
      <!-- 表单区域-->
      <el-form
        :model="addCateFrom"
        :rules="addCateFromRules"
        ref="addCateFromRef"
        label-width="100px"
      >
        <!-- 输入框 -->
        <el-form-item label="活动名称" prop="cat_name">
          <el-input v-model="addCateFrom.cat_name"></el-input>
        </el-form-item>
        <!-- 级联选择器 -->
        <el-form-item label="父级分类" prop="cat_name">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="props"
            :clearable="true"
            @change="parentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editGoodsDialogVisible" width="50%">
      <!-- 编辑商品的主体区域
       -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editGoodsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: '',
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类数据
      cateList: [],
      // 商品分类数据总数
      total: 0,
      //   带有树形控件得表格列
      columns: [
        {
          label: '商品名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      //   控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      // 添加表单的信息
      addCateFrom: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      //添加分类表单的验证规则
      addCateFromRules: {
        cat_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 获取父级分类数据
      parentCateList: [],
      // 级联选择器选择的数据
      selectedKeys: [],
      // 级联选择器的配置对象
      props: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        checkStrictly: true
      },
      // 根据id获取到的商品的信息
      goodsName: '',
      // 控制编辑商品对话框的显示与隐藏
      editGoodsDialogVisible: false,
      // 编辑表单
      editForm: {
        cat_name: ''
      },
      // 编辑商品表单的验证规则
      editFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      // 商品的id
      cateId: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      //   console.log(res)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 监听分页大小改变
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    // 监听页数的改变
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    // 展示添加对话框
    async showAddCateDialog() {
      // 获取父级商品分类
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败')
      }
      this.parentCateList = res.data
      //   console.log(this.parentCateList)
      this.addCateDialogVisible = true
    },
    // 父级分类发生变化时，修改提交表单的数据
    parentCateChanged() {
      if (this.selectedKeys.length > 0) {
        this.addCateFrom.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addCateFrom.cat_level = this.selectedKeys.length
      } else {
        this.addCateFrom.cat_pid = 0
        this.addCateFrom.cat_level = 0
      }

      console.log(this.selectedKeys)
    },
    // 添加分类
    addCate() {
      console.log(this.addCateFrom)
      this.$refs.addCateFromRef.validate(async valid => {
        if (!valid) {
          return this.$message.info('请填写完整信息')
        }
        const { data: res } = await this.$http.post('categories', this.addCateFrom)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.addCateDialogVisible = false
        this.getCateList()
      })
    },
    // 监听添加分类对话框的关闭
    addCateDialogClosed() {
      this.selectedKeys = []
      this.addCateFrom.cat_level = 0
      this.addCateFrom.cat_pid = 0
      this.$refs.addCateFromRef.resetFields()
    },
    // 删除商品分类元素
    async deleteHandle(cateId) {
      console.log(cateId)
      const resultStr = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (resultStr !== 'confirm') {
        return this.$message.error('已取消删除操作')
      }
      const { data: res } = await this.$http.delete(`categories/${cateId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败')
      }
      this.getCateList()
    },
    // 展示编辑商品对话框
    async showEditGoodsDialog(goods) {
      this.cateId = goods.cat_id
      this.editForm.cat_name = goods.cat_name
      this.editGoodsDialogVisible = true
    },
    async addEditForm() {
      const { data: res } = await this.$http.put(`categories/${this.cateId}`, this.editForm)
      if (res.meta.status !== 200) {
        return this.$message.error('编辑用户分类失败')
      }
      this.$message.success('编辑用户分类成功')
      this.getCateList()
      this.editGoodsDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
